import axios from 'axios'
import { showMessage } from './status'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 设置接口超时时间
axios.defaults.timeout = 60000
axios.defaults.baseURL = 'http://jinchao.yunctime.com'

// 添加一个标志位来跟踪是否已经跳转到登录页
let isRedirectingToLogin = false

// 请求拦截
axios.interceptors.request.use(
  (config) => {
    // 如果正在跳转登录页，则取消后续请求
    if (isRedirectingToLogin) return

    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截
axios.interceptors.response.use(
  (response) => {
    const { data } = response
    const { code, msg } = data
    if (+code === 401 || +code === 403) {
      localStorage.removeItem('token')
      handleUnauthorized(msg)
      return Promise.reject(response)
    } else if (+code === 500) {
      ElMessage.error(msg || `后端接口未知异常`)
    }
    return response
  },
  (error) => {
    if (axios.isCancel(error)) {
      return Promise.reject(error)
    }

    const { response } = error
    if (response) {
      if (response.status === 401) {
        handleUnauthorized()
        return Promise.reject(error)
      }

      const message = showMessage(response.status)
      ElMessage.error(message || `后端接口未知异常`)
    } else {
      ElMessage.error('网络连接异常，请检查网络')
    }
    return Promise.reject(error)
  }
)

// 统一处理未授权的函数
function handleUnauthorized(msg?: string) {
  if (isRedirectingToLogin) return

  isRedirectingToLogin = true

  // 确保当前路由不是登录页才跳转
  if (router.currentRoute.value.path !== '/login') {
    router
      .replace({
        path: '/login'
      })
      .then(() => {
        // 强制刷新页面以确保完全重新加载
        ElMessage.error(msg || '登录已过期，请重新登录')
        localStorage.removeItem('token')
        setTimeout(() => {
          window.location.reload()
        }, 1000)
      })
      .catch(() => {
        // 如果路由跳转失败，直接重定向
        window.location.href = '/login'
      })
      .finally(() => {
        setTimeout(() => {
          isRedirectingToLogin = false
        }, 1000)
      })
  } else {
    isRedirectingToLogin = false
  }
}
// 封装请求并导出
export function request(data: any) {
  return new Promise((resolve, reject) => {
    const promise = axios(data)
    promise
      .then((res: any) => {
        resolve(res.data)
      })
      .catch((err: any) => {
        reject(err)
      })
  })
}
